package org.example.videotran.service;

import org.example.videotran.exception.AppException;
import org.example.videotran.exception.AppExceptionCodeMsg;
import org.example.videotran.utils.JwtToken;
import org.example.videotran.utils.MD5Utils;
import org.example.videotran.pojo.User;
import org.example.videotran.pojo.dto.UserDto;
import org.example.videotran.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository userRepository;


    @Override
    public String loginByPhone(UserDto userDto) {
        if (userRepository.findByPhone(userDto.getPhone()).isEmpty()){
            throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS);
        }

        userDto.setPassword(MD5Utils.Encrypt(userDto.getPassword()));

        Optional<User> user = userRepository.findByPhoneAndPassword(userDto.getPhone(), userDto.getPassword());

        if (user.isPresent()) {
            return JwtToken.createToken(user.get());
        }

        return null;
    }

    @Override
    public String loginByEmail(UserDto userDto) {
        if (userRepository.findByEmail(userDto.getPhone()).isEmpty()){
            throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS);
        }

        userDto.setPassword(MD5Utils.Encrypt(userDto.getPassword()));

        Optional<User> user = userRepository.findByEmailAndPassword(userDto.getEmail(), userDto.getPassword());

        if (user.isPresent()) {
            return JwtToken.createToken(user.get());
        }

        return null;
    }

    @Override
    public User getUser(String token) {
        String uid = JwtToken.extractUid(token);

        Optional<User> user = userRepository.findById(Integer.valueOf(uid));

        return user.get();

    }

    @Override
    public boolean register(UserDto userDto) {

        User user = new User();

        try {
            BeanUtils.copyProperties(userDto,user);

            user.setPassword(MD5Utils.Encrypt(user.getPassword()));

            user.setRole(0);

            Optional<User> userNew = userRepository.findByPhoneAndPassword(user.getPhone(), user.getPassword());

            if (userNew.isPresent()) {
                return false;
            }

            userRepository.save(user);

            return true;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }


}
